<template>
  <div class="order-page">
    <headBar  isBack="show">
      <div slot="xm-header-center">
        <div class="xm-header-title" >采购单</div>
      </div>
      <div slot="xm-header-right"></div>
    </headBar>
    <div v-show="hasPurchase">
      <div class="cart-list">
        <ul>
          <li v-for="item in purchaseList">
            <div class="address">
              <i class="icon icon-selected2" :class="{'active' : item.isChecked}" @click="selectOne(item)"></i>{{item.addressName}}
              <!--<span class="fr" @click="deleteOrder(item.addressId)">删除</span>-->
            </div>
            <ol>
              <li class="flex border-bottom" v-for="wareInfo in item.wareInfoList">
                <img :src="wareInfo.url">
                <div class="cart-center flex-1">
                  <h3> <span class="zy">自营</span>{{wareInfo.wareName}}</h3>
                  <p class="price">￥{{wareInfo.pricePiece | money}} <span>{{wareInfo.numberPerBox}}袋/件</span></p>
                </div>
                <div class="cart-right">
                  <div class="num-div">
                    <span @click="numMinus(wareInfo,item)">-</span><span class="num">{{wareInfo.number}}</span><span @click="numPlus(wareInfo,item)">+</span>
                  </div>
                  <span class="delete" @click="deleteOrder(wareInfo.id)">删除</span>
                </div>
              </li>
            </ol>
            <div class="compute">小计：<span>￥{{item.amountTotal | money}}</span></div>
          </li>
        </ul>
      </div>

      <section class="bottom-section">
        <div class="foot-bar flex">
          <label class="flex-1" @click="selectAll"><i class="icon icon-selected2" :class="{'active' : isSelectAll}"></i>全选</label>
          <a class="balance" :class="{'not-click': !isJoin}" @click="purchasePromptPresale">
            去结算
            <priceShow :price="totalMoney" unitName="" v-show="isJoin"></priceShow>
          </a>
        </div>
      </section>
    </div>
    <!--采购单为空-->
    <nodata textContent="没有采购单数据" v-show="!hasPurchase"></nodata>

    <!--商品库存不足-->
    <div class="alert-div" v-show="isPreWare">
      <div class="alert-fade" @click="isPreWare=false"></div>
      <div class="alert-box pre-sale">
        <div class="tit">以下商品库存不足，预计3-7天送达 <i class="icon icon-close" @click="isPreWare=false"></i></div>
        <div class="goods-list">
          <div class="item border-bottom" v-for="item in preWareName">{{item.wareName}}</div>
        </div>
        <div class="alert-opt flex">
          <div class="btn2 flex-1" @click="isPreWare=false">取消</div>
          <div class="btn3 flex-1" @click="establishOrder">确定</div>
        </div>
      </div>
    </div>
    <!--以下商品不足起批量-->
    <div class="alert-div" v-show="isBatches">
      <div class="alert-fade" @click="isBatches=false"></div>
      <div class="alert-box pre-sale">
        <div class="tit">以下商品不足起批量<i class="icon icon-close" @click="isBatches=false"></i></div>
        <div class="goods-list">
          <div class="item border-bottom" v-for="item in batchesName">{{item.wareName}}<span>{{item.numberWholesale}}件起批</span></div>
        </div>
        <div class="alert-opt flex">
          <div class="btn3 flex-1" @click="establishOrder">确定</div>
        </div>
      </div>
    </div>
    <xm-loading v-show="loading"></xm-loading>
    <div class="foot-blank"></div>
    <footBar curPage="purchase"></footBar>
  </div>
</template>
<script>
  let userName = '';
  export default {
    props: {},
    data() {
      return {
        loading: true,
        hasPurchase: true, // 是否有采购单数据
        isPreWare: false,
        isBatches: false, //满足起批量
        isSelectAll:true,
        totalMoney: 0,//总金额
        btnName: '去结算',
        purchaseList: [],
        preWareName: [],
        batchesName:[],
        isJoin:true,
      };
    },
    methods: {
      //获取采购列表
      getPurchaseList(){
        getPurchaseList().then(data=>{
          this.loading = false;
          if(data.returnCode == '000000'){
            data.result.purchaseItem.forEach(item=>{
                this.$set(item,"isChecked",true);
            });
            this.purchaseList = data.result.purchaseItem;
            if(this.purchaseList.length == 0){
                this.hasPurchase = false;
            }
            setTimeout(()=>{
                this.compute();
            },20);
          }else if(data.returnCode == '100001'){
            this.hasPurchase = false;
          }
        })
      },
      /**
       * －
       * */
      numMinus(wareInfo,item){
          var minNum=wareInfo.numberWholesale || 1 ;
          if(wareInfo.number>minNum){
              wareInfo.number--;
              this.computeOne(item);
          }
      },
      /**
       * +
       * */
      numPlus(wareInfo,item){
          wareInfo.number++;
        this.computeOne(item);
      },
      //全部选中
      selectAll(){
         this.isSelectAll=!this.isSelectAll;
        [].forEach.call(this.purchaseList, (select)=>{
          select.isChecked = this.isSelectAll;
        });
        this.isJoin=this.isSelectAll;
        this.compute();
      },
      /**
       * 单个
       * */
      selectOne(item){
          item.isChecked=!item.isChecked;
          this.isCheckedAll();
          this.compute();
      },
      /*全选是否选中*/
      isCheckedAll(){
          var checkedArr=[];
          [].forEach.call(this.purchaseList, (select)=>{
              if(select.isChecked){
                  checkedArr.push(select);
              }
          });
          this.isJoin=checkedArr.length==0 ? false : true;
          if(checkedArr.length<this.purchaseList.length){
              this.isSelectAll=false;
          }else {
              this.isSelectAll=true;
          }
      },
      /**
       * 计算单个地址的总价格
       * */
      computeOne(item){
          console.log(item);
          var oneTotal=0;
          [].forEach.call(item.wareInfoList, (ware)=> {
              oneTotal+=ware.number*ware.pricePiece;
          });
          item.amountTotal=oneTotal;
          this.compute();
      },
      //计算总价格
      compute(){
          this.totalMoney = 0;
          [].forEach.call(this.purchaseList, (select)=> {
              if (select.isChecked) {
                  this.totalMoney += select.amountTotal;
              }
          })
      },
      /**
       * 采购单详情
       * @param <string> 地址id
       * */
//      detail(addressId){
//        this.$router.push({name: 'purchaseDetail', params: {addressId: addressId}});
//      },
      /**
       * @todo 删除采购单
       * @param <string> 地址id
       * */
      deleteOrder(id){
        MessageBox.confirm('确定执行此操作?').then(action => {
          delShoppingCartById({id: id}).then(data=>{
            if(data.returnCode == '000000'){
                  location.reload();
              }
          })
        }).catch(cancel =>{
          console.log(cancel);
        });
      },

      //生成订单
      establishOrder(){
        let addressIds = [];
        [].forEach.call(this.purchaseList, (select)=> {
            if (select.isChecked) {
                addressIds.push(select.addressId);
            }
        });
        if(addressIds.length == 0) return;
        establishOrder({addressIds: addressIds.join(',')}).then(data=>{
          if(data.returnCode == '000000'){
            this.$router.push({name: 'orderOrder', params: {orderCode: data.result.orderMainId,orderSource:0}});
          }else{
            Toast(data.errorMsg)
          }
        });
      },
      /**
       * 验证采购单是否采取预售
       * */
      purchasePromptPresale(){
        let addressIds = [];
        [].forEach.call(this.purchaseList, (select)=> {
            if (select.isChecked) {
                addressIds.push(select.addressId);
            }
        });
        if(addressIds.length == 0) return;

        purchasePromptPresale({addressIds: addressIds.join(',')}).then(data=>{
            if(data.returnCode == '000000'){
              this.$router.push({name: 'orderOrder', params: {orderCode: data.result.orderMainId,orderSource:0}});
            }else if(data.returnCode == '100012'){//预售
                this.isPreWare = true;
                this.preWareName = data.result.wareNameList;
            }else if(data.returnCode == '100013'){//起批量不足
                this.isBatches = true;
                this.batchesName = data.result.wareQpNameList;
            } else{
              Toast(data.errorMsg)
            }
        });
      }
    },
    filters: {
      filterNameSub(name){
        if(name != userName){
          return name;
        }
        return '自己';
      }
    },
    created() {
      userName = Cookie.get('userName');
      this.getPurchaseList();
//      let parentId = Cookie.get('parentId');
//      if(parentId != 'null' && parentId != ''){
//        this.isParent = false;
//        this.inAuditPruchase();
//      }
    },
    mounted(){

    },
    components: {
    }
  };
</script>
<style lang="less" scoped>
  .order-page .noData{
    margin-top: 2.1rem;
  }
  .order-page{
    .cart-list ul li .address i{
      font-size: .44rem;
    }
    .cart-list ul ol li .cart-right{
      position: relative;
      .num-div{
        margin-top:-.4rem;
      }
      .delete{
        position: relative;
        top: .31rem;
        font-size: .24rem;
        color: #333;
      }
    }
  }
  .bottom-section{
    height: .98rem;
    .foot-bar{
      height: .98rem;
      bottom: .98rem;
      background: #FFFFFF;
      box-shadow: 0 -2px 4px 0 rgba(0,0,0,0.10);
      label{
        i{
          position: relative;
          top: .08rem;
          margin-right: .16rem;
          font-size: .44rem;
          color: #ccc;
          &.active{
            color: #FF2F51;
          }
          &.active:before{
            content: "\E673";
          }
        }
        line-height: .8rem;
        padding-left: .24rem;
        font-size: .24rem;
        color: #333333;
        text-align: left;
      }
      .balance{
        width: 3.6rem;
        height: .98rem;
        line-height: .98rem;
        text-align: center;
        background: #FF4A4A;
        color: #fff;
        box-shadow: 0 -2px 4px 0 rgba(0,0,0,0.10);
        .priceShow{
          color: #fff;
        }
        &.not-click{
          background: #E8EDF2;
          color: #CED4D9;
        }
      }
    }
  }
</style>
